from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
from django.http import HttpResponseForbidden, JsonResponse, HttpResponseServerError, HttpResponseNotFound
from django.contrib.auth.decorators import login_required
from django.contrib.auth import login, logout, authenticate
from django.core.exceptions import ObjectDoesNotExist
from django.core.files.base import ContentFile
from pydocx import PyDocX
from django.utils.safestring import mark_safe
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from weekly.models import *
import codecs
import time
import os
# import markdown

# Create your views here.
# Home Page
def home(request):
    a_top = Article.objects.filter(top=True).order_by('-upload_time')
    articles = Article.objects.all().filter(top=False).order_by('-upload_time')
    paginator = Paginator(articles, 5)
    pages = request.GET.get('page', 1)
    try:
        ats = paginator.page(pages)
    except PageNotAnInteger:
        ats = paginator.page(1)
    except EmptyPage:
        ats = paginator.page(paginator.num_pages)
    return render(request, 'index.html', {'tops': a_top, 'articles': ats})

# Login Page
def Login(requset):
    return render(requset, 'login.html')

# Article Upload Page
def article_upload(request):
    g = Group.objects.all()
    return render(request, 'article_upload.html', {'groups': g})

# Article Detail Page
def article_detail(request, num, year, half, week):
    try:
        mem_num = Member.objects.get(number=num)
        yr = Year.objects.get(year=year, first_half=half)
        wk = Week.objects.get(week=week)
        a = Article.objects.get(member=mem_num, year=yr, week=wk)

        if bool(a.doc):
            doc_html = PyDocX.to_html(a.doc.path)
            doc_html = doc_html.replace('<html>', '').replace('</html>', '').replace('<head>', '').replace('</head>', '')
            doc_html = doc_html.replace('<meta charset="utf-8" />', '').replace('<body>', '').replace('</body>', '')
            start = doc_html.find('</style>')
            style = doc_html[:start+8]
            doc_html = doc_html.replace(style, '')
            doc_html = mark_safe(doc_html)
        else:
            doc_html = None

        if bool(a.md):
            input_file = codecs.open(a.md.path, mode="r", encoding="utf-8")
            text = input_file.read()
            md_html = text
            # md_html = markdown.markdown(text)
            # md_html = mark_safe(md_html)
        else:
            md_html = None

        a.click_increase()

        return render(request, 'article_detail.html', {'article': a, 'doc': doc_html, 'md': md_html})
    except ObjectDoesNotExist:
        return HttpResponseNotFound()

# Archive Page
def archive(request):
    g = Group.objects.all()
    y = time.strftime('%Y')
    w = time.strftime('%W')
    w = int(w) - 7
    if (w + 7) > 32:
        h = 2
    else:
        h = 1
    try:
        yr = Year.objects.get(year=y, first_half=h)
        wk = Week.objects.get(week=w)
        articles = Article.objects.filter(year=yr, week=wk)
        return render(request, 'archive.html', {'groups': g, 'articles': articles})
    except ObjectDoesNotExist:
        return HttpResponseNotFound()

# Personal List Page
def person_list(request):
    g = Group.objects.all()
    return render(request, 'person_list.html', {'groups': g})

# API List
# API.Login
@csrf_exempt
def api_login(request):
    if request.is_ajax():
        if request.method == "POST":
            name = request.POST['username']
            pwd = request.POST['password']
            user = authenticate(username=name, password=pwd)
            if user is not None and user.is_active:
                login(request, user)
                return JsonResponse({
                    "status": '1',
                    "message": '登录成功'
                })
            else:
                return JsonResponse({
                    "status": '0',
                    "message": '登录失败'
                })
        else:
            return HttpResponseForbidden()
    else:
        return HttpResponseServerError()

# API.Logout
@csrf_exempt
@login_required(redirect_field_name='', login_url='/login/')
def api_logout(request):
    if request.is_ajax():
        if request.method == "POST":
            signal = request.POST['signal']
            if signal == "OUT":
                try:
                    logout(request)
                    return JsonResponse({
                        "status": "OK"
                    })
                except:
                    return JsonResponse({
                        "status": "WTF"
                    })
            else:
                return JsonResponse({
                    "status": "WTF"
                })
        else:
            return HttpResponseForbidden()
    else:
        return HttpResponseServerError()

# API.Article_Upload
@csrf_exempt
def api_article_upload(request):
    if request.is_ajax():
        if request.method == 'POST':
            member = request.POST['member']
            md_code = request.POST['md_code']
            doc = request.FILES.get('doc')
            md = request.FILES.get('md')

            try:
                name = Member.objects.get(member=member)
            except ObjectDoesNotExist:
                return JsonResponse({'status': '成员不存在'})

            # 自动计算注入第几周
            # 进入下一个学期之后需要手动更改
            wt = time.strftime('%W')
            wt = int(wt) - 7
            try:
                wk = Week.objects.get(week=wt)
            except ObjectDoesNotExist:
                return JsonResponse({'status': '提交时间超出范围'})

            # 自动计算注入年份
            yt = time.strftime('%Y')
            try:
                if (wt + 7) > 32:
                    yr = Year.objects.get(year=yt, first_half=2)
                else:
                    yr = Year.objects.get(year=yt, first_half=1)
            except ObjectDoesNotExist:
                return JsonResponse({'status': '提交时间超出范围'})

            art, created = Article.objects.get_or_create(member=name, week=wk, year=yr)

            if md_code != '':
                art.md.save('editor.md', ContentFile(md_code))

            if doc is not None:
                art.doc = doc
                art.save()

            if md is not None:
                art.md = md
                art.save()

            return JsonResponse({'status': 'OK'})
        else:
            return HttpResponseForbidden()
    else:
        return HttpResponseServerError()